﻿using Google.Protobuf;
using System;

namespace Message.Base
{
    //消息类
    public abstract class BaseMessage
    {
        private int messageID;
        public BaseMessage(int messageId)
        {
            messageID = messageId;
        }

        /// <summary>
        /// 得到消息标识
        /// </summary>
        /// <returns></returns>
        public int MessageID => messageID;

        /// <summary>
        /// 获取消息长度
        /// </summary>
        /// <returns></returns>
        public abstract int GetBytesLength();
        /// <summary>
        /// 得到传输消息体
        /// </summary>
        /// <returns></returns>
        public abstract byte[] GetBytes();


        /// <summary>
        /// 消息写入方法
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="beginIndex"></param>
        /// <param name="length"></param>
        public abstract void WriteIn(byte[] buffer, int beginIndex, int length);

        public abstract void Reset();


    }

    //提供一个泛型版本,用于自定义消息
    public abstract class BaseMessage<T> : BaseMessage where T : IMessage, new()
    {
        public T Data = new();

        protected BaseMessage(int messageId) : base(messageId)
        { }

        public override byte[] GetBytes()
        {
            byte[] buffer = new byte[GetBytesLength()];
            BitConverter.GetBytes(MessageID).CopyTo(buffer, 0);
            BitConverter.GetBytes(GetBytesLength()).CopyTo(buffer, 4);
            if (buffer.Length > 8)
                Data.ToByteArray().CopyTo(buffer, 8);
            return buffer;

        }

        /// <summary>
        /// 这个Data带了一定的长度
        /// </summary>
        /// <returns></returns>
        public override int GetBytesLength() => 8 + (Data == null ? 0 : Data.CalculateSize());

    }

}
